import os
import requests

root_path = 'G:/TieBaImg/MeiNv/'


#  下载图片
def download_img(url, pathname):
    root = root_path + pathname+"/"
    path = root + url.split("/")[-1]
    print(url)
    try:
        if not os.path.exists(root):
            os.makedirs(root)
        if not os.path.exists(path):
            r = requests.get(url)
            r.raise_for_status()
            print('picture name :'+path + ' dir path :'+root)
            # 使用with语句可以不用自己手动关闭已经打开的文件流
            with open(path, "wb") as f:  # 开始写文件，wb代表写二进制文件
                f.write(r.content)
            print("爬取完成")
        else:
            print("文件已存在")
    except Exception as e:
        print("爬取失败:" + str(e))

